<template>
  <el-menu
    v-if="menuLoaded && menuTree.length > 0"
    :default-active="activeMenu"
    class="el-menu-vertical"
    :router="false"
    :unique-opened="true"
    :collapse="isCollapse"
  >
    <template v-for="item in menuTree" :key="item.id">
      <el-sub-menu 
        v-if="item.children && item.children.length > 0" 
        :index="item.route || item.id.toString()"
      >
        <template #title>
          <el-icon><Menu /></el-icon>
          <span @click="handleMenuItemClick('', item)">{{ item.name }}</span>
        </template>
        <el-menu-item
          v-for="child in item.children"
          :key="child.id"
          :index="child.route || child.id.toString()"
          @click="handleMenuItemClick(child.route, child)"
        >
          <el-icon><Document /></el-icon>
          <span>{{ child.name }}</span>
        </el-menu-item>
      </el-sub-menu>
      <el-menu-item 
        v-else 
        :index="item.route || item.id.toString()"
        @click="handleMenuItemClick(item.route, item)"
      >
        <el-icon><Menu /></el-icon>
        <span>{{ item.name }}</span>
      </el-menu-item>
    </template>
  </el-menu>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { Menu, Document } from '@element-plus/icons-vue'
import { getMenuTree } from '../api/menu'
import type { MenuItem } from '../types/menu'

const props = defineProps<{
  isCollapse: boolean
  lazy?: boolean
}>()

const menuTree = ref<MenuItem[]>([])
const menuLoaded = ref(false)
const activeMenu = ref('')

const emit = defineEmits<{
  (e: 'menu-select', menu: MenuItem): void
}>()

const loadMenuTree = async () => {
  menuTree.value = await getMenuTree()
  menuLoaded.value = true
}

const handleMenuItemClick = (route: string, menu: MenuItem) => {
  if (route) {
    activeMenu.value = route
  }
  emit('menu-select', menu)
}

// 监听 lazy 属性的变化
watch(() => props.lazy, (newVal) => {
  if (newVal && !menuLoaded.value) {
    loadMenuTree()
    menuLoaded.value = true
  }
})

// 如果不是延迟加载，则在组件挂载时加载数据
onMounted(() => {
  if (!props.lazy) {
    loadMenuTree()
  }
})
</script>

<style scoped>
.el-menu-vertical:not(.el-menu--collapse) {
  width: 200px;
}

.el-menu-item.is-active {
  color: var(--el-menu-active-color) !important;
  background-color: var(--el-menu-hover-bg-color) !important;
}
</style> 